package com.scwatch.core.web.back;

import com.scwatch.common.orm.RowSide;
import com.scwatch.common.web.Servlets;
import com.scwatch.core.constant.Constants;
import com.scwatch.core.domain.Model;
import com.scwatch.core.domain.Node;
import com.scwatch.core.domain.Programback;
import com.scwatch.core.domain.User;
import com.scwatch.core.html.HtmlService;
import com.scwatch.core.service.*;
import com.scwatch.core.support.Context;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.scwatch.core.constant.Constants.*;

/**
 * 节目回看
 * Created by rh006 on 2017/7/27.
 */
@Controller
@RequestMapping("/core/programback")
public class ProgrambackController {
    private static final Logger logger = LoggerFactory
            .getLogger(ProgrambackController.class);

    /**
     * 节目回看，查询频道
     * @param pageable 分页对象
     * @param request 请求对象
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("list.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:list")
    public String list(
            @PageableDefault(sort = "id", direction = Sort.Direction.ASC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        Integer siteId = Context.getCurrentSiteId();
        params.put("EQ_site.id",new  String[]{String.valueOf(siteId)});
        Page<Programback> pagedList = programBackService.findAll(params, pageable);
        modelMap.addAttribute("pagedList", pagedList);

//        PageRequest tvpageable=new PageRequest(0,30000,new Sort(Sort.Direction.DESC,"time"));
//        Map<String,String[]> paramMap=new HashMap<String,String[]>();
//        paramMap.put("EQ_site.id",new  String[]{String.valueOf( siteId)});
//        Page<Sinatv> tvpagedList = sinatvService.findAll(paramMap, tvpageable);
//        modelMap.addAttribute("sinatvList",tvpagedList.getContent());
        return "core/program/programback_list";
    }

    /**
     * 跳转到创建节目频道页面
     * @param id
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("create.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:create")
    public String create(Integer id, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        if (id != null) {
            Programback bean = programBackService.get(id);
            modelMap.addAttribute("bean", bean);
        }
//        //卫视数据
//        PageRequest pageable=new PageRequest(0,30000,new Sort(Sort.Direction.DESC,"time"));
//        Map<String,String[]> paramMap=new HashMap<String,String[]>();
//        paramMap.put("EQ_site.id",new  String[]{String.valueOf( siteId)});
//        Page<Sinatv> pagedList = sinatvService.findAll(paramMap, pageable);
//        modelMap.addAttribute("sinatvList",pagedList.getContent());
        modelMap.addAttribute(OPRT, CREATE);
        return "core/program/programback_form";
    }

    /**
     * 跳转到修改节目频道页面
     * @param id
     * @param position
     * @param pageable
     * @param request
     * @param modelMap
     * @return 结果页面
     */
    @RequestMapping("edit.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:edit")
    public String edit(
            Integer id,
            Integer position,
            @PageableDefault(sort = "id", direction = Sort.Direction.DESC) Pageable pageable,
            HttpServletRequest request, org.springframework.ui.Model modelMap) {
        Integer siteId = Context.getCurrentSiteId();
        Programback bean = programBackService.get(id);
        Map<String, String[]> params = Servlets.getParamValuesMap(request,
                Constants.SEARCH_PREFIX);
        RowSide<Programback> side = programBackService.findSide(params, bean, position,
                pageable.getSort());

//        //卫视数据
//        PageRequest tvpageable=new PageRequest(0,30000,new Sort(Sort.Direction.DESC,"time"));
//        Map<String,String[]> paramMap=new HashMap<String,String[]>();
//        paramMap.put("EQ_site.id",new  String[]{String.valueOf( siteId)});
//        Page<Sinatv> pagedList = sinatvService.findAll(paramMap, tvpageable);
//        modelMap.addAttribute("sinatvList",pagedList.getContent());
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute("side", side);
        modelMap.addAttribute("position", position);
        modelMap.addAttribute(OPRT, EDIT);
        return "core/program/programback_form";
    }

    /**
     * 节目频道保存
     * @param bean 频道数据对象
     * @param redirect
     * @param sinatvId
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("save.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:save")
    public String save(Programback bean, String redirect,Integer sinatvId,
                       HttpServletRequest request, RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        User user = Context.getCurrentUser();
        bean.setTime(new Date());
        bean.setUser(user);

//        if(sinatvId==null){
//            ra.addFlashAttribute(MESSAGE, OPERATION_FAILURE);
//            return "redirect:create.do";
//        }
//        Sinatv tv=sinatvService.get(sinatvId);
//        if(tv==null){
//            ra.addFlashAttribute(MESSAGE, OPERATION_FAILURE);
//            return "redirect:create.do";
//        }
//        bean.setSinatv(tv);
        programBackService.save(bean, siteId, user);
        logService.operation("opr.programback.add", bean.getName(), null,
                bean.getId(), request);
        logger.info("save Programback, name={}.", bean.getName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else if (Constants.REDIRECT_CREATE.equals(redirect)) {
            return "redirect:create.do";
        } else {
            ra.addAttribute(bean.getId());
            return "redirect:edit.do";
        }
    }

    /**
     * 修改节目频道
     * @param bean 节目数据对象
     * @param sinatvId 节目频道id
     * @param position
     * @param redirect
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("update.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:update")
    public String update(@ModelAttribute("bean") Programback bean,Integer sinatvId,
                         Integer position, String redirect, HttpServletRequest request,
                         RedirectAttributes ra) {
//        if(sinatvId!=null){
//            Sinatv tv=sinatvService.get(sinatvId);
//            if(tv==null){
//                ra.addFlashAttribute(MESSAGE, OPERATION_FAILURE);
//                ra.addAttribute("id", bean.getId());
//                ra.addAttribute("position", position);
//                return "redirect:edit.do";
//            }
//            bean.setSinatv(tv);
//        }
        programBackService.update(bean);
        logService.operation("opr.programback.edit", bean.getName(), null,
                bean.getId(), request);
        logger.info("update Programback, name={}.", bean.getName());
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:edit.do";
        }
    }

    /**
     * 删除节目频道
     * @param ids 数据id
     * @param request
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("delete.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:delete")
    public String delete(Integer[] ids, HttpServletRequest request,
                         RedirectAttributes ra) {
        Programback[] beans = programBackService.delete(ids);
        for (Programback bean : beans) {
            logService.operation("opr.programback.delete", bean.getName(),
                    null, bean.getId(), request);
            logger.info("delete Programback, name={}.", bean.getName());
        }
        ra.addFlashAttribute(MESSAGE, DELETE_SUCCESS);
        return "redirect:list.do";
    }

    /**
     * 生成节目回看json数据
     * @param modelMap
     * @param ra
     * @return 结果页面
     */
    @RequestMapping("generationBack.do")
    @RequiresRoles("super")
    @RequiresPermissions("core:programback:generationBack")
    public String generationBack(org.springframework.ui.Model modelMap,RedirectAttributes ra) {
        Integer siteId = Context.getCurrentSiteId();
        Integer[] nodeIds=getNodeIdsByFlag(Constants.MODEL_TV_of_yesterday,siteId);
        if(nodeIds!=null && nodeIds.length>0){
            htmlService.makeNode(nodeIds[0]);
        }
        ra.addAttribute(OPRT, CREATE);
        return "redirect:list.do";
    }

    private Integer[] getNodeIdsByFlag(String modelFlag,Integer siteId) {
        Integer [] nodeIds=null;
        Map<String,String[]> paramMap=new HashMap<String,String[]>();
        paramMap.put("EQ_flag",new String[]{modelFlag});
        List<Model> models=modelService.findList(siteId,null,paramMap,null);

        paramMap=new HashMap<String,String[]>();
        String[] idsStr;
        if(models!=null && models.size()>0){
            idsStr=new String[models.size()];
            for(int i=0;i<models.size();i++){
                idsStr[i]=models.get(i).getId().toString();
            }
            paramMap.put("EQ_nodeModel.id",idsStr);
        }
        Sort paramSort=new Sort(Sort.Direction.ASC, "treeNumber", "id");
        List<Node>  currentNodeList=nodeQuery.findList(siteId,null,
                null,null,true,
                paramMap, paramSort);
        if(currentNodeList!=null){
            nodeIds=new Integer[currentNodeList.size()];
            for(int i=0;i<currentNodeList.size();i++){
                nodeIds[i]=(currentNodeList.get(i).getId());
            }
        }
        return  nodeIds;
    }

    @ModelAttribute("bean")
    public Programback preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? programBackService.get(oid) : null;
    }

    @Autowired
    private OperationLogService logService;
    @Autowired
    private ProgramBackService programBackService;
    @Autowired
    private ModelService modelService;
    @Autowired
    private HtmlService htmlService;
    @Autowired
    private NodeQueryService nodeQuery;
    @Autowired
    private SinatvService sinatvService;


}
